import QtQuick 2.0

Item {
    id: control
    width: 180
    height: 160
    property real radius: 106
    property int currentAngle: 0
    property real warnAngle: 30
    property real maxAngle: 40

    property string iconSource

    Canvas{
        id: canvas
        anchors.fill: parent
        contextType:  "2d";
        onPaint: {
            var ctx = getContext("2d");
            ctx.reset();
            ctx.save()
            if(currentAngle>=0){
                if(currentAngle < warnAngle){
                    ctx.strokeStyle = Qt.rgba(0, 1, 1, 0.4)
                    ctx.fillStyle = Qt.rgba(0, 1, 1, 0.4)
                }else{
                    ctx.strokeStyle = Qt.rgba(1, 0, 0, 0.4)
                    ctx.fillStyle = Qt.rgba(1, 0, 0, 0.4)
                }
                ctx.beginPath()
                ctx.moveTo(110,110)
                ctx.arc(110, 110, radius, Math.PI, (180+currentAngle)/180*Math.PI);
                ctx.closePath()
                ctx.fill()
                ctx.stroke()
            }else{
                if(currentAngle > -warnAngle){
                    ctx.strokeStyle = Qt.rgba(0, 1, 1, 0.4)
                    ctx.fillStyle = Qt.rgba(0, 1, 1, 0.4)
                }else{
                    ctx.strokeStyle = Qt.rgba(1, 0, 0, 0.4)
                    ctx.fillStyle = Qt.rgba(1, 0, 0, 0.4)
                }
                ctx.beginPath()
                ctx.moveTo(0,110)
                ctx.arc(0, 110, control.radius, 0, currentAngle/180*Math.PI,true)
                ctx.closePath()
                ctx.fill()
                ctx.stroke()
            }
            ctx.restore()


            ctx.save()
            if(currentAngle >= 0){
                ctx.translate(110,110)
                ctx.rotate(currentAngle/180*Math.PI)
                ctx.drawImage(iconSource, -110, -55)
            }else{
                ctx.translate(0,110)
                ctx.rotate(currentAngle/180*Math.PI)
                ctx.drawImage(iconSource, 0, -55)
            }

            ctx.restore()


            ctx.save()
            ctx.fillStyle = "white"
            ctx.font = "30px Aldrich"
            ctx.textAlign = "center"
            ctx.fillText(String(currentAngle) + "°" , 140, 110)
            ctx.restore()
        }

        onImageLoaded: requestPaint()
        Component.onCompleted: {
            loadImage(iconSource)
        }
    }

    onCurrentAngleChanged:
    {
        if(currentAngle > 0 && currentAngle > maxAngle){
            currentAngle = maxAngle
        }else if(currentAngle < 0 && currentAngle < -maxAngle){
            currentAngle = -maxAngle
        }

        canvas.requestPaint()
    }
}
